package org.shop.controller.liveManager;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.dao.JoinInfoMapper;
import org.shop.entity.ActivityInfo;
import org.shop.entity.ShufflingInstall;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.ActivityInfoService;
import org.shop.service.JoinInfoService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.coobird.thumbnailator.Thumbnails;

@Controller
public class LiveManagerActivityController {

private static Logger logger = LogManager.getLogger(LiveManagerActivityController.class);
	
	@Autowired
	private ActivityInfoService activityInfoService;
	@Autowired
	private JoinInfoService joinInfoService;
	@Autowired
	private JoinInfoMapper joinInfoMapper;
	
	/**
	 * 获取活动列表
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/getActivityInfoList")
	@ResponseBody
	public Map<String,Object> getActivityInfoList(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
	 	String currentPage = req.getParameter("offset");
        String pageSize = req.getParameter("limit");
        String title = req.getParameter("title");
		try{
			Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("startPage", Integer.parseInt(currentPage));
            paramMap.put("pageSize", Integer.parseInt(pageSize));
            paramMap.put("title", title);
            map = activityInfoService.getActivityInfoList(paramMap);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	/**
	 * 获取活动的照片
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/getActivityInfoImg")
	@ResponseBody
	public Map<String,Object> getActivityInfoImg(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Long activityId = Long.parseLong(req.getParameter("activityId"));
		List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
		try {
			 ActivityInfo selectByPrimaryKey = activityInfoService.selectByPrimaryKey(activityId);
			String imgPost = selectByPrimaryKey.getPhoto();
			String[] imgList = imgPost.split(",");
			System.err.println(imgList.length);
			String url = "http://" + req.getServerName() + ":"+ req.getServerPort()+ req.getContextPath()+"/";
			for(int i = 0;i<imgList.length;i++) {
				Map<String,Object> map2 = new HashMap<String,Object>();
				map2.put("alt", "活动图片-"+(i+1));
				map2.put("pid", i);
				map2.put("src", url+"common/getGoodsPhoto?photoUrl="+imgList[i]);
				map2.put("thumb", url+"common/getGoodsPhoto?photoUrl="+imgList[i]);
				data.add(map2);
			}
			map.put("title", "活动相册");
			map.put("id", activityId);
			map.put("start", 0);
			map.put("data", data);
		}catch(Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	
	
	/**
	 * 新建活动日程
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/addActivityInfo")
	@ResponseBody
	public Map<String,Object> addActivityInfo(HttpServletRequest req) {
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		//转换成多部分request  
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
		//获取的值
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String,Object> map = new HashMap<String,Object>();
		String title = multiRequest.getParameter("title");
		String activityPlace = multiRequest.getParameter("activityPlace");
		String activityTime = multiRequest.getParameter("activityTime");
		String deadline = multiRequest.getParameter("deadline");
		String maxPeople = multiRequest.getParameter("maxPeople");
		String name2 = multiRequest.getParameter("name");
		String phone = multiRequest.getParameter("phone");
		String email = multiRequest.getParameter("email");
		String registrationWay = multiRequest.getParameter("registrationWay");
		String editorValue = multiRequest.getParameter("editorValue");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String photoStr="";
		FTPClient ftpClient =null;
		InputStream is = null;
		try{
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			//取得request中的所有文件名
    			Iterator<String> iter = multiRequest.getFileNames();
    			//创建ftp链接
    			String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
    			while(iter.hasNext()){
    				String name=iter.next();
					//取得上传文件
    				List<MultipartFile> fileList = multiRequest.getFiles(name);
    				if(fileList!=null){
    					for(MultipartFile file:fileList){
    						if(file != null){
    							//取得当前上传文件的文件名称
    	    					String myFileName = file.getOriginalFilename();
    	    					myFileName=FtpUtil2.generateFileName(myFileName);
    	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
    	    					if(myFileName.trim() !=""){
    	    						myFileName=FtpUtil2.generateFileName(myFileName);
    	    						 //按照比例进行缩小和放大
                                    is=file.getInputStream();
                                    int len=is.available();
                                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                    if(len/1024>700) {//kb
                                    	//按照比例进行缩小和放大
                                        Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                    }
    	    						FtpUtil2.upload(myFileName, is, ftpClient);
    	    						if("".equals(photoStr)){
    	    							photoStr+=ftp_photoDirectory+"/"+myFileName;
    	    						}else{
    	    							photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
    	    						}
    	    					}
    						}
    					}
    				}
				}
    			ActivityInfo ai =new ActivityInfo();
    			ai.setTitle(title);
    			ai.setActivityPlace(activityPlace);
    			ai.setActivityTime(activityTime);
    			ai.setDeadline(sdf.parse(deadline));
    			ai.setMaxPeople((byte) Integer.parseInt(maxPeople));
    			ai.setName(name2);
    			ai.setPhone(phone);
    			ai.setEmail(email);
    			ai.setRegistrationWay((byte) Integer.parseInt(registrationWay));
    			ai.setContent(editorValue);
    			ai.setUserId(ud.getUserId());
    			ai.setUserName(ud.getUserName());
    			ai.setPhoto(photoStr);
    			int num = activityInfoService.insertSelective(ai );
    			map.put("num", num);
    		}
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("num", 0);
    	}finally {
    		try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
		}
		return map;
	}
	
	
	/**
	 * 删除活动
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/delActivityInfo")
	@ResponseBody
	public Map<String,Object> delActivityInfo(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Long activityId = Long.parseLong(req.getParameter("activityId"));
		try {
			ActivityInfo ai = new ActivityInfo();
			ai.setActivityId(activityId);
			ai.setState((byte) 0);
			int num = activityInfoService.updateByPrimaryKeySelective(ai );
			if(num>0) {
				joinInfoService.delJoinInfo(activityId);
				map.put("num", 1);
			}else {
				map.put("num", 0);
			}
		}catch(Exception e) {
			map.put("num", 0);
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	
	/**
	 * 获取活动的详细信息
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/getActivityInfo")
	@ResponseBody
	public Map<String,Object> getActivityInfo(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Long activityId = Long.parseLong(req.getParameter("activityId"));
		try {
			ActivityInfo selectByPrimaryKey = activityInfoService.selectByPrimaryKey(activityId);
			map.put("ai", selectByPrimaryKey);
		}catch(Exception e) {
			map.put("ai", null);
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	/**
	 * 编辑活动日程
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/editActivityInfo")
	@ResponseBody
	public Map<String,Object> editActivityInfo(HttpServletRequest req) {
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		//转换成多部分request  
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
		//获取的值
		//获取登录人用户信息
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		Map<String,Object> map = new HashMap<String,Object>();
		String title = multiRequest.getParameter("title");
		String activityPlace = multiRequest.getParameter("activityPlace");
		String activityTime = multiRequest.getParameter("activityTime");
		String deadline = multiRequest.getParameter("deadline");
		String maxPeople = multiRequest.getParameter("maxPeople");
		String name2 = multiRequest.getParameter("name");
		String phone = multiRequest.getParameter("phone");
		String email = multiRequest.getParameter("email");
		String registrationWay = multiRequest.getParameter("registrationWay");
		String editorValue = multiRequest.getParameter("editorValue");
		Long activityId = Long.parseLong(multiRequest.getParameter("activityId"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String photoStr="";
		FTPClient ftpClient =null;
		InputStream is = null;
		try{
    		//判断 request 是否有文件上传,即多部分请求
    		if(multipartResolver.isMultipart(req)){
    			//取得request中的所有文件名
    			Iterator<String> iter = multiRequest.getFileNames();
    			//创建ftp链接
    			String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
    			ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
    			while(iter.hasNext()){
    				String name=iter.next();
					//取得上传文件
    				List<MultipartFile> fileList = multiRequest.getFiles(name);
    				if(fileList!=null){
    					for(MultipartFile file:fileList){
    						if(file != null){
    							//取得当前上传文件的文件名称
    	    					String myFileName = file.getOriginalFilename();
    	    					myFileName=FtpUtil2.generateFileName(myFileName);
    	    					//如果名称不为"",说明该文件存在，否则说明该文件不存在
    	    					if(myFileName.trim() !=""){
    	    						myFileName=FtpUtil2.generateFileName(myFileName);
    	    						 //按照比例进行缩小和放大
                                    is=file.getInputStream();
                                    int len=is.available();
                                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                                    if(len/1024>700) {//kb
                                    	//按照比例进行缩小和放大
                                        Thumbnails.of(is).scale(0.2f).toOutputStream(bos);
                                        is = new ByteArrayInputStream(bos.toByteArray());
                                    }
    	    						FtpUtil2.upload(myFileName, is, ftpClient);
    	    						if("".equals(photoStr)){
    	    							photoStr+=ftp_photoDirectory+"/"+myFileName;
    	    						}else{
    	    							photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
    	    						}
    	    					}
    						}
    					}
    				}
				}
    			ActivityInfo ai =new ActivityInfo();
    			ai.setTitle(title);
    			ai.setActivityPlace(activityPlace);
    			ai.setActivityTime(activityTime);
    			ai.setDeadline(sdf.parse(deadline));
    			ai.setMaxPeople((byte) Integer.parseInt(maxPeople));
    			ai.setName(name2);
    			ai.setPhone(phone);
    			ai.setEmail(email);
    			ai.setRegistrationWay((byte) Integer.parseInt(registrationWay));
    			ai.setContent(editorValue);
    			ai.setUserId(ud.getUserId());
    			ai.setUserName(ud.getUserName());
    			ai.setPhoto(photoStr);
    			ai.setActivityId(activityId);
    			int num = activityInfoService.updateByPrimaryKeySelective(ai);
    			map.put("num", num);
    		}
		}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    		map.put("num", 0);
    	}finally {
    		try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
		}
		return map;
	}
	
	/**
	 * 验证活动是否可以删除 与编辑
	 * @param req
	 * @return
	 */
	@RequestMapping("liveManager/verifyActivity")
	@ResponseBody
	public Map<String,Object> verifyActivity(HttpServletRequest req){
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		Long activityId = Long.parseLong(req.getParameter("activityId"));
		try {
			paramMap.put("activityId", activityId);
			int joinInfoCount = joinInfoMapper.getJoinInfoCount(paramMap);
			if(joinInfoCount>0) {
				ActivityInfo selectByPrimaryKey = activityInfoService.selectByPrimaryKey(activityId);
				if(selectByPrimaryKey.getDeadline().getTime()<=new Date().getTime()) {
					//活动结束
					map.put("num", 1);
				}else {
					//活动未结束
					map.put("num", 0);
				}
			}else {
				map.put("num", 1);
			}
		}catch(Exception e) {
			map.put("num", -1);
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	
	
	
}
